package com.hethongviet.preventing.page;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hethongviet.preventingmachine.AppMain;
import com.hethongviet.preventingmachine.Constants;
import com.hethongviet.preventingmachine.R;
import com.hethongviet.preventingmachine.Utils;
import com.hethongviet.preventingmachine.helps.CommonUtils;
import com.hethongviet.preventingmachine.helps.Device;
import com.hethongviet.preventingmachine.helps.DeviceSQLite;
import com.hethongviet.preventingmachine.helps.dialog.DialogMessageBack;
import com.hethongviet.preventingmachine.helps.dialog.DialogMessageTimeOut;
import com.hethongviet.preventingmachine.helps.OnSMSMessageListener;
import com.hethongviet.preventingmachine.helps.SMSHelperDoor;
import com.hethongviet.preventingmachine.helps.SmsReceiverDoor;
import com.hethongviet.preventingmachine.helps.TabMenu;
import com.hethongviet.preventingmachine.models.Number;
import com.hethongviet.preventingmachine.models.SMS;
import com.hethongviet.preventingmachine.models.Tab;

/** Main page of application */
public class PageAdminActivity extends Activity implements OnSMSMessageListener
{
	/**Tab constant*/
	private final static int TAB_DEVICE = 0;
	private final static int TAB_NUMBERS_CONTROL = TAB_DEVICE + 1;
	private final static int TOTAL_TABS = TAB_NUMBERS_CONTROL + 1;

	/**Database*/
	private DeviceSQLite _DeviceSQLite = null;
	private Device _Device = null;

	/**List view of control numbers*/
	private LinearLayout _LayoutListNumbersControl = null;

	/**Tab content*/
	private ScrollView _LayoutTabDevice = null;
	private ScrollView _LayoutTabNumbersControl = null;
	
	/**Tab button*/
	private Button _ButtonTabDevice = null;
	private Button _ButtonTabNumbersControl = null;

	/**Main buttons*/
	private Button _ButtonNumberControlAdd = null;
	private Button _ButtonNumberControlSave = null;
	private Button _ButtonChangePassword = null;
	private Button _ButtonGetLog = null;

	/**List of control numbers*/
	private List<Number> _NumbersControlList = null;
	
	/**Received SMS results*/
	private String smsResultStr = null;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		Utils.prepareWindow(this);

		setContentView(R.layout.page_admin);

		_LayoutListNumbersControl = (LinearLayout) findViewById(com.hethongviet.doorcontroller.admin.R.id.list_numbers_control);
		_LayoutTabDevice = (ScrollView) findViewById(com.hethongviet.doorcontroller.admin.R.id.layout_tab_device);
		_LayoutTabNumbersControl = (ScrollView) findViewById(com.hethongviet.doorcontroller.admin.R.id.layout_tab_numbers_control);
		_ButtonTabDevice = (Button) findViewById(com.hethongviet.doorcontroller.admin.R.id.button_tab_device);
		_ButtonTabNumbersControl = (Button) findViewById(com.hethongviet.doorcontroller.admin.R.id.button_tab_numbers_control);

		_ButtonNumberControlAdd = (Button) findViewById(com.hethongviet.doorcontroller.admin.R.id.button_number_control_add);
		_ButtonNumberControlSave = (Button) findViewById(com.hethongviet.doorcontroller.admin.R.id.button_number_control_save);

		_ButtonChangePassword = (Button) findViewById(com.hethongviet.doorcontroller.admin.R.id.button_device_change_pincode);
		_ButtonGetLog = (Button) findViewById(com.hethongviet.doorcontroller.admin.R.id.button_device_view_log_file);

		initTab();
		initDB();

		try
		{
			_Device = _DeviceSQLite.getAll().get(0);
		} catch (Exception e)
		{
			e.printStackTrace();
			finish();
			return;
		}

		Utils.debug("password = " + _Device.getPin());
		Utils.debug("number = " + _Device.getNumber());

		SMSHelperDoor.setPassword(_Device.getPin());
		SMSHelperDoor.setDeviceNumber(_Device.getNumber());

		String numberStr = getIntent().getStringExtra("numbers");

		if (!TextUtils.isEmpty(numberStr))
		{
			String[] numbers = numberStr.split("[ "
					+ SMSHelperDoor.CODE_SEPARATE + "]");

			if (numbers == null || numbers.length == 0)
			{
				Utils.debug("Have no number!!!!!!!!!");
			}
			else
			{

				if (_NumbersControlList == null)
					_NumbersControlList = new ArrayList<Number>();

				for (String string : numbers)
				{
					Number number = new Number();
					number.setActive(true);
					number.setNumber(string);
					_NumbersControlList.add(number);
				}
			}
		}

		showListNumbersControl();

		prepareForDeviceChange();

		prepareForAddNumberControl();
	}

	@Override
	protected void onResume()
	{

		SmsReceiverDoor.setOnSMSMessageListener(this);
		SMSHelperDoor.setActivity(this);

		super.onResume();
	}

	private void prepareForDeviceChange()
	{
		_ButtonChangePassword.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(PageAdminActivity.this,
						PageChangePincodeActivity.class);
				intent.putExtra(Constants.EXTRA_PASSWORD, _Device.getPin());
				intent.putExtra(Constants.EXTRA_REQUEST,
						Constants.REQUEST_CHANGE_PASSWORD);
				startActivity(intent);
			}
		});

		_ButtonGetLog.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(PageAdminActivity.this,
						PageViewLogFileActivity.class);
				startActivity(intent);
			}
		});

	}

	private void prepareForAddNumberControl()
	{

		if (_NumbersControlList == null
				|| _NumbersControlList.size() <= Constants.MAX_PHONE_CONTROL)
		{
			_ButtonNumberControlAdd.setVisibility(View.VISIBLE);
		}
		else
			_ButtonNumberControlAdd.setVisibility(View.GONE);

		_ButtonNumberControlAdd.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(PageAdminActivity.this,
						PageAddContactActivity.class);
				startActivityForResult(intent,
						PageAddContactActivity.REQUEST_ADD);
			}
		});

		_ButtonNumberControlSave.setVisibility(View.GONE);
		_ButtonNumberControlSave.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				/* Send SMS */
				if (_NumbersControlList == null
						|| _NumbersControlList.size() == 0)
				{
					Utils.debug("Error: numbers null!!!!!!");
					return;
				}

				Utils.showProgress(PageAdminActivity.this);

				SMSHelperDoor.setupNumberControl(_NumbersControlList);
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode == RESULT_OK)
		{
			if (data != null)
			{
				String nameStr = data.getStringExtra(PageAddContactActivity.EXTRA_NAME);
				String numberStr = data.getStringExtra(PageAddContactActivity.EXTRA_NUMBER);
				if (_NumbersControlList != null)
				{
					for (Number number : _NumbersControlList)
					{
						if (number.getNumber().equals(numberStr))
						{
							showDialogWithCatch(R.string.message_error_input_number_already);
							return;
						}
					}
				}
				else
				{
					_NumbersControlList = new ArrayList<Number>();
				}

				final Number number = new Number();
				number.setNumber(numberStr);
				number.setName(nameStr);
				number.setActive(true);

				_NumbersControlList.add(number);

				/* Add to GUI */
				final ViewHolderNumber holder = new ViewHolderNumber(
						PageAdminActivity.this, number,
						_LayoutListNumbersControl);

				holder.addView(SMSHelperDoor.CODE_SYNCHRONIZE_NUMBERS_CONTROL,
						R.string.message_fail_synchronize_numbers_control,
						_ButtonNumberControlSave);

				_ButtonNumberControlSave.setVisibility(View.VISIBLE);
			}
		}
	}

	private void initDB()
	{
		_DeviceSQLite = new DeviceSQLite(this,
				AppMain.getInstance().getDBName());
		_DeviceSQLite.open();
		_DeviceSQLite.close();
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_success_change_name
				|| id == R.string.message_success_change_password
				|| id == R.string.message_success_change_number)
		{
			return new DialogMessageBack(this, false, id, false);
		}
		else if (id == R.string.message_success_add_numbers_control)
		{
			final DialogMessageTimeOut dialogMessageTimeOut = new DialogMessageTimeOut(
					this, smsResultStr, true);

			final TimerTask timerTask = new TimerTask()
			{
				@Override
				public void run()
				{
					runOnUiThread(new Runnable()
					{
						@Override
						public void run()
						{
							dialogMessageTimeOut.hide();
						}
					});
				}
			};

			dialogMessageTimeOut.setTimeTask(timerTask);

			return dialogMessageTimeOut;
		}
		else if (id == R.string.message_error_input_too_long_number)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MAX_NUMBER), false);
		}
		else if (id == R.string.message_error_input_too_short_number)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MIN_NUMBER), false);
		}
		else if (id == R.string.message_error_input_too_long_name)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MAX_NAME), false);
		}
		else if (id == R.string.message_error_input_too_short_name)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MIN_NAME), false);
		}
		else if (id == R.string.message_error_input_too_long_address)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MAX_ADDRESS), false);
		}
		else if (id == R.string.message_error_input_too_short_address)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MIN_ADDRESS), false);
		}
		else
		{
			return new DialogMessageBack(this, true, id, false);
		}
	}

	private void initTab()
	{
		/* Process for tab menu */
		Tab[] tabs = new Tab[TOTAL_TABS];

		tabs[TAB_DEVICE] = new Tab();
		tabs[TAB_DEVICE].setButton(_ButtonTabDevice);
		tabs[TAB_DEVICE].setViewContain(_LayoutTabDevice);

		tabs[TAB_NUMBERS_CONTROL] = new Tab();
		tabs[TAB_NUMBERS_CONTROL].setButton(_ButtonTabNumbersControl);
		tabs[TAB_NUMBERS_CONTROL].setViewContain(_LayoutTabNumbersControl);

		new TabMenu(tabs, R.drawable.button_tab2,
				R.drawable.button_tab2_highlight);

	}

	@Override
	public void onSMSMessageIncoming(SMS sms)
	{
		String message = CommonUtils.prepareMessage(sms.getMessage());

		Utils.debug("Message receive = " + message);

		if (Utils.isStringNull(message))
		{
			Utils.debug("ERROR----- wrong message! NULL");
			return;
		}
		String codeSMS = SMSHelperDoor.transaction.getCodeSend();
		if (codeSMS.equals(SMSHelperDoor.CODE_SETUP_PHONE_CONTROL))
		{
			Utils.hideProgressDialog();

			for (Number number : _NumbersControlList)
			{
				number.setActive(true);
			}

			smsResultStr = message;
			showDialogWithCatch(R.string.message_success_add_numbers_control);

			_ButtonNumberControlSave.setVisibility(View.GONE);
		}

	}

	private void showDialogWithCatch(int id)
	{
		try
		{
			showDialog(id);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private void showListNumbersControl()
	{
		_LayoutListNumbersControl.removeAllViews();
		if (_NumbersControlList == null || _NumbersControlList.size() == 0)
			return;

		int total = _NumbersControlList.size();

		for (int index = 0; index < total; index++)
		{
			final Number number = _NumbersControlList.get(index);

			final ViewHolderNumber holder = new ViewHolderNumber(this, number,
					_LayoutListNumbersControl);

			holder.addView(SMSHelperDoor.CODE_SYNCHRONIZE_NUMBERS_CONTROL,
					R.string.message_fail_synchronize_numbers_control,
					_ButtonNumberControlSave);
			if (_ButtonNumberControlSave.getVisibility() == View.GONE
					&& !number.isActive())
			{
				_ButtonNumberControlSave.setVisibility(View.VISIBLE);
			}
		}

	}

	
	private class ViewHolderNumber
	{
		Activity activity = null;
		Number number = null;
		LinearLayout layoutListNumbers = null;

		Button buttonDelete = null;
		TextView textNumber = null;
		TextView textName = null;

		ViewHolderNumber(Activity activity, Number number,
				LinearLayout layoutListNumbers)
		{
			this.activity = activity;
			this.number = number;
			this.layoutListNumbers = layoutListNumbers;
		}

		void addView(final String codeSMS, final int messageFailId,
				final Button buttonNumberSave)
		{
			final LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View view = layoutInflater.inflate(
					R.layout.layout_one_number, null);

			buttonDelete = (Button) view.findViewById(R.id.layout_one_number_button_delete);
			textNumber = (TextView) view.findViewById(R.id.layout_one_number_number);

			textNumber.setText(number.getNumber());
			textName = (TextView) view.findViewById(R.id.layout_one_number_name);

			textName.setText(number.getName());

			buttonDelete.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0)
				{
					if (_NumbersControlList != null)
					{
						for (Number numberSrc : _NumbersControlList)
						{
							if (numberSrc.getNumber().equals(number.getNumber()))
							{
								numberSrc.setActive(false);
								break;
							}
						}
					}

					layoutListNumbers.removeView(view);
					buttonNumberSave.setVisibility(View.VISIBLE);
				}
			});
			layoutListNumbers.addView(view);
		}
	}
}
